package controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

public class ProfileServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String[] listError = new String[3];
		request.setAttribute("listError", listError);
		try {
			request.getRequestDispatcher("/profile.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		String oldpassword = request.getParameter("oldpassword");
		String newpassword = request.getParameter("newpassword");
		String repassword = request.getParameter("repassword");
		
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.sendRedirect("/");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		String[] listError = new String[3];
		try {
			if(oldpassword!=null&&!Utils.md5(oldpassword).equals(dbObject.get("password").toString()))
			{
				listError[0]="Old password incorrect !";
			} else {
				if(newpassword!=null&&newpassword.equals(""))
				{
					listError[1]="New password is not empty !";
				} else {
					if(!newpassword.equals(repassword))
					{
						listError[2]="Confirm password incorrect !";
					}
				}
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		if(listError[0]==null&&listError[1]==null&&listError[2]==null)
		{
			DBCollection collection = Data.data("users");
			try {
				dbObject.put("password", Utils.md5(newpassword));
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			collection.save(dbObject);
			request.setAttribute("success", "Change password success");
		}
		
		request.setAttribute("listError", listError);
		
		try {
			request.getRequestDispatcher("/profile.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
